package com.china08.yxyapi.service.mg.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.entity.mg.mistakes.StuMistakesQues;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.repository.mg.mistakes.StuMistakesQuesRepository;
import com.china08.yxyapi.service.mg.StuMistakesQuesService;

/**
 * 学生错题统计
 * 
 * @author LiuWeidong
 *
 */
@Service
public class StuMistakesQuesServiceImpl implements StuMistakesQuesService {

    @Autowired
    private HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Autowired
    private HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    public MongoOperations mongoOperations;

    @Autowired
    private StuMistakesQuesRepository stuMistakesQuesRepository;

    /**
     * 开始统计
     */
    public void stuMistakesQuesStatistics() {
        getTaskIdforStatusOfFinished();
    }

    /**
     * 根据同步状态获取作业任务 （获取已批阅的任务）
     */
    @Override
    public void getTaskIdforStatusOfFinished() {
        for (;;) {
            Criteria criteria = new Criteria();
            // 查询条件
            // 同步状态
            criteria.and("statusOfFinished").is(2);
            criteria.andOperator(new Criteria().orOperator(Criteria.where("synchStuMistakes").is(0),
                    Criteria.where("synchStuMistakes").is(null)));
            // 错题状态

            Query query = new Query();
            query.addCriteria(criteria);

            query.with(new Sort(new Order(Direction.DESC, "createdDate")));
            query.limit(1000);
            List<HomeworkTaskReport> dataList = mongoOperations.find(query, HomeworkTaskReport.class);
            if (dataList.size() <= 0) {
                break;
            }
            for (HomeworkTaskReport htr : dataList) {
                mstakesQues(htr.getId());
                htr.setSynchStuMistakes(1);
                homeworkTaskReportRepository.save(htr);
            }
        }
    }

    @Override
    public void mstakesQues(String reportId) {
        Criteria criteria = new Criteria();
        criteria.and("reportId").is(reportId);

        // 查询为题型为选择题 且passed为0
        Criteria criteriaOrForAnd = new Criteria();
        criteriaOrForAnd.andOperator(Criteria.where("passed").is(0), new Criteria()
                .orOperator(Criteria.where("questionType").is("0"), Criteria.where("questionType").is("1")));

        //
        criteria.andOperator(
                new Criteria().orOperator(Criteria.where("synchStuMistakes").is(0),
                        Criteria.where("synchStuMistakes").is(null)),
                new Criteria().orOperator(criteriaOrForAnd, Criteria.where("mark").lt(5)));

        // 状态
        Query query = new Query();
        query.addCriteria(criteria);
        query.with(new Sort(new Order(Direction.DESC, "createdDate")));
        List<HomeworkTaskReportQues> dataList = mongoOperations.find(query, HomeworkTaskReportQues.class);
        stuMistakesQues(dataList);
    }

    @Override
    public void stuMistakesQues(List<HomeworkTaskReportQues> dataList) {
        Map<String, List<HomeworkTaskReportQues>> stuMistakesQuesMap = dataList.stream()
                .collect(Collectors.groupingBy(HomeworkTaskReportQues::getStudentId));

        for (Entry<String, List<HomeworkTaskReportQues>> stu : stuMistakesQuesMap.entrySet()) {
            for (HomeworkTaskReportQues homeworkTaskReportQues : stu.getValue()) {

                String studentId = homeworkTaskReportQues.getStudentId();
                String quesId = homeworkTaskReportQues.getQuesId();
                String id = studentId + quesId;

                StuMistakesQues stuMistakesQues = stuMistakesQuesRepository.findById(id);
                if (stuMistakesQues != null) {

                    List<Integer> knowIdList = stuMistakesQues.getKnowIdLst();
                    if (homeworkTaskReportQues.getKnowIdLst() != null) {
                        for (Integer knowId : homeworkTaskReportQues.getKnowIdLst()) {
                            if (!knowIdList.contains(knowId)) {
                                knowIdList.add(knowId);
                            }
                        }
                        stuMistakesQues.setKnowIdLst(knowIdList);
                    }

                    if (homeworkTaskReportQues.getKnowNameLst() != null) {
                        List<String> knowNameList = stuMistakesQues.getKnowNameLst();
                        for (String knowName : homeworkTaskReportQues.getKnowNameLst()) {
                            if (!knowNameList.contains(knowName)) {
                                knowNameList.add(knowName);
                            }
                        }
                        stuMistakesQues.setKnowNameLst(knowNameList);
                    }

                    // 排除发送者ID重复
                    List<String> publishUserIdLst = stuMistakesQues.getPublishUserId();
                    if (!publishUserIdLst.contains(homeworkTaskReportQues.getPublishUserId())) {
                        publishUserIdLst.add(homeworkTaskReportQues.getPublishUserId());
                    }
                    stuMistakesQues.setPublishUserId(publishUserIdLst);
                    stuMistakesQues.setStatus(0);

                    stuMistakesQues.setPublishDate(homeworkTaskReportQues.getCreatedDate());
                } else {
                    stuMistakesQues = new StuMistakesQues();
                    stuMistakesQues.setId(id);
                    stuMistakesQues.setStudentId(studentId);
                    stuMistakesQues.setStudentNick(homeworkTaskReportQues.getStudentName());
                    stuMistakesQues.setQuesId(quesId);
                    stuMistakesQues.setAnswerOfMy(homeworkTaskReportQues.getAnswerOfMy());
                    stuMistakesQues.setAnswerText(homeworkTaskReportQues.getAnswerText());
                    stuMistakesQues.setAnswerImgs(homeworkTaskReportQues.getAnswerImgs());
                    List<String> sources = new ArrayList<String>();
                    sources.add("00");
                    stuMistakesQues.setSources(sources);
                    List<String> publishUserId = new ArrayList<String>();
                    publishUserId.add(homeworkTaskReportQues.getPublishUserId());
                    stuMistakesQues.setPublishUserId(publishUserId);
                    stuMistakesQues.setStage(homeworkTaskReportQues.getStage());
                    stuMistakesQues.setSubject(homeworkTaskReportQues.getSubject());
                    stuMistakesQues.setQuestionType(homeworkTaskReportQues.getQuestionType());
                    stuMistakesQues.setKnowIdLst(homeworkTaskReportQues.getKnowIdLst());
                    stuMistakesQues.setKnowNameLst(homeworkTaskReportQues.getKnowNameLst());
                    stuMistakesQues.setStatus(0);
                    stuMistakesQues.setFocus(0);
                    stuMistakesQues.setPublishDate(homeworkTaskReportQues.getCreatedDate());

                    stuMistakesQues.setCreatedDate(new Timestamp(new Date().getTime()));
                }
                homeworkTaskReportQues.setSynchStuMistakes(1);
                homeworkTaskReportQuesRepository.save(homeworkTaskReportQues);
                stuMistakesQuesRepository.save(stuMistakesQues);
            }
        }

    }
}
